package auth.util

import auth.entity.SecRole
import org.apache.log4j.Logger
import org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib

/**
 * User: pradeep
 * Date: Jul 21, 2010
 * Time: 3:17:17 PM
 * To get role specific details.
 */
class RoleUtil {

  Logger gLogger = Logger.getLogger(RoleUtil.class)
  private static RoleUtil instance = null
  private static def roleList
  private static def authorityDescriptionMap
  def g = new ApplicationTagLib()

  /**
   * returns the instance
   * @return
   */
  public static RoleUtil getInstance() {
    if (instance == null) {
      instance = new RoleUtil()
      instance.getAll()
    }

    return instance
  }

    /**
     * list all roles
     */
  private void getAll(){
    roleList = SecRole.getAll()
  }

    /**
     * generate role map
     * @return
     */
  public Map getAllAuthorityDescriptionMap()
  {
      if(roleList==null){
        getAll()
      }

      authorityDescriptionMap = new HashMap()
      roleList?.each {role->
        authorityDescriptionMap.put(role.authority,role.description!=null && role.description.trim().length() > 0 ? role.description : role.authority   )
      }
      
      return authorityDescriptionMap
  }

    /**
     * to get configuration description
     * @param authorityStr
     * @param delimiter
     * @return
     */
  public String getConfigAttributeDescription(String authorityStr,String delimiter = ","){
    String  authorityDescription = "";
    if(authorityDescriptionMap==null){
       getAllAuthorityDescriptionMap()
    }
    String temp
    authorityStr.split(delimiter).each {string->

       string = string.trim()

       temp = authorityDescriptionMap?.get(string)!=null? authorityDescriptionMap?.get(string): string

       if(authorityDescription.trim().length() > 0 ){
         authorityDescription += delimiter + " " + temp
       }else{
         authorityDescription = temp          
       }
    }

    if(authorityDescription==null || authorityDescription.trim().length() == 0){
      authorityDescription = authorityStr
    }

    return authorityDescription
  }


}
